package com.ypf.rpc.loadBalancer;

import com.ypf.rpc.manager.register.pojo.RegisterInfo;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 轮询负载均衡算法
 */
public class RoundRobinRule implements LoadBalancer {

    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    /**
     * 防止Interget越界 超过Integer最大值
     * @return
     */
    public final int getAndIncrement() {
        int current;
        int next;

        do {
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE?0:current+1;
        }while (!atomicInteger.compareAndSet(current,next));

        return current;
    }


    @Override
    public RegisterInfo getRegisterInfo(List<RegisterInfo> registerInfoList) {
        return registerInfoList.get(getAndIncrement()%registerInfoList.size());
    }
}
